import { goodsList, goodAdd, goodsdel, goodsremove } from '@/services/goods';
import { message } from 'antd';

export default {
  namespace: 'goods',

  state: {
    list: [],
    pagination: [],
    data: [],
    brand_data: [],
    treeData: [],
  },

  effects: {
    *fetchGoodsList({ payload }, { call, put }) {
      const response = yield call(goodsList, payload);
      if (response && response.status === 'success') {
        yield put({
          type: 'goodslist',
          payload: response.data,
        });
      }
    },
    *goodadd({ payload }, { call, put }) {
      const response = yield call(goodAdd, payload);
      if (response && response.status === 'success') {
        message.success('添加成功');
        const two_response = yield call(goodsList);
        if (two_response && two_response.status === 'success') {
          yield put({
            type: 'goodslist',
            payload: two_response.data,
          });
        }
      }
    },
    *gooddel({ payload }, { call, put }) {
      const response = yield call(goodsdel, payload);
      if (response && response.status === 'success') {
        yield put({
          type: 'goodsdel',
          ...payload,
        });
        message.success('删除成功');
      }
    },
    *goodremove({ payload }, { call, put }) {
      const response = yield call(goodsremove, payload);
      if (response && response.status === 'success') {
        const two_response = yield call(goodsList);
        if (two_response && two_response.status === 'success') {
          message.success('修改成功');
          yield put({
            type: 'goodslist',
            payload: two_response.data,
          });
        }
      }
    },
  },
  reducers: {
    goodslist(state, action) {
      return {
        ...state,
        list: action.payload,
        pagination: action.payload.pagination,
        data: action.payload.crowd_data,
        brand_data: action.payload.brand_data,
        treeData: action.payload.treeData,
      };
    },
    goodsdel(state, action) {
      console.log(state, action);
      for (let i = 0; i < state.list.list.length; i++) {
        if (state.list.list[i].key === action.id) {
          state.list.list.splice(i, 1);
        }
      }
      return {
        ...state,
      };
    },
  },
};
